import { Module } from 'vuex'
import RootStateTypes from '../../interface'
import TabsStateType, { TabState } from './interface'

function GetTabs(): TabState[] {
    let tabs = JSON.parse(sessionStorage.getItem('App.Tabs.List') || '[]')
    return tabs.map((tab: any) => {
        return {
            name: tab.name,
            title: tab.title,
        }
    })
}

const tabs: Module<TabsStateType, RootStateTypes> = {
    namespaced: true,
    state: (): TabsStateType => ({
        tabs: GetTabs(),
        last: sessionStorage.getItem('App.Tabs.Last') || '',
    }),
    mutations: {
        add(state, tab: TabState) {
            if (state.tabs.findIndex(t => t.name === tab.name) == -1) {
                state.tabs.push(tab)
                sessionStorage.setItem('App.Tabs.List', JSON.stringify(state.tabs))
            }
        },
        close(state, name: string) {
            let index = state.tabs.findIndex(tab => tab.name === name)
            if (index >= 0) {
                state.tabs.splice(index, 1)
                sessionStorage.setItem('App.Tabs.List', JSON.stringify(state.tabs))
            }
        },
        setLast(state, name: string) {
            if (name) {
                state.last = name
                sessionStorage.setItem('App.Tabs.Last', state.last)
            }
        },
    },
}

export default tabs
